package com.sj.uabrowser.app;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/**
 * Created by Administrator on 2017/2/20.
 */

public class NetworkUtils {
    public static final String TAG = "NetworkUtils";

    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) {
        } else {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }

        return false;
    }

    public static int getNetworkType(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) {

        } else {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return info[i].getType();
                    }
                }
            }
        }

        return -1;
    }

    public static boolean isMobileNetwork(Context context) {
        return isNetworkAvailable(context) && (ConnectivityManager.TYPE_MOBILE == getNetworkType(context));
    }

    public static boolean isWifiNetwork(Context context) {
        return isNetworkAvailable(context) && (ConnectivityManager.TYPE_WIFI == getNetworkType(context));
    }

    public static int getNetworkNumber(Context context) {
        context = context.getApplicationContext();
        if (context != null && isNetworkAvailable(context)) {
            if (ConnectivityManager.TYPE_WIFI == getNetworkType(context)) {
                return 1;
            } else if (ConnectivityManager.TYPE_MOBILE == getNetworkType(context)) {
                return 2;
            }
        }
        return 0;
    }
}
